//
//  WPRefreshControl.swift
//  WB
//
//  Created by 汪鹏 on 2017/1/15.
//  Copyright © 2017年 汪鹏. All rights reserved.
//  自定义刷新控件

import UIKit

/// 最大的拖拽距离
private let maxOffSetY:CGFloat = 44

///  描述刷新的状态
///
/// - normal: 一般状态
/// - draging: 下拉状态
/// - startRefresh: 开始刷新
enum refreshStatus {
    
    case normal // 普通状态，什么都不做
    
    case draging // 超过临界点如果放手，开始刷新
    
    case startRefresh // 开始刷新数据
    
}

class WPRefreshControl: UIControl {

    // 表示正在刷新的状态
    var isRefreshing:Bool = false
    
    // 记录父视图,适用于UITableView/UICollectionView
    private weak var scrollView:UIScrollView?
    
    lazy private var refreshView:WPRefreshView = WPRefreshView.refreshView()
    
    init(){
       super.init(frame: CGRect())
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        // newSuperview也会为nil
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        
        scrollView = sv
        
        // kvo 监听
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
     
        guard let sv = scrollView else {
            return
        }
        
        let height = -(sv.contentOffset.y + sv.contentInset.top)
        
        if height < 0 {
            return
        }
        
        frame = CGRect(x: 0, y: -height, width: sv.bounds.width, height: height)
        
        /// 判断临界点
        if sv.isDragging { // 正在拖拽
            
            if height >= maxOffSetY && (refreshView.refreshState == .normal) {
                
                refreshView.refreshState = .draging
                
            }else if(height < maxOffSetY && (refreshView.refreshState == .draging)) {
                
                refreshView.refreshState = .normal
                
            }
        }else{
            
           // 放手--判断是否过了零界点
            if refreshView.refreshState == .draging {
                
                // 开始刷新(刷新结束之后要讲状态设置为.normal)
                beginRefreshing()
                
                // 发送事件
                sendActions(for: .valueChanged)
            }
            
        }

    }
    
    
    /// 本视图从父控件上移除
    override func removeFromSuperview() {
        
        // 移除KVO监听(此时superView还不为空，super.removeFromSuperview()之后就为空)
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        
       super.removeFromSuperview()
    }
    
    
    /// 开始刷新
    func beginRefreshing() {
        
        guard let sv = scrollView else{
            return
        }
        
        // 正在刷新直接返回
        if refreshView.refreshState == .startRefresh {
            return
        }
        
        refreshView.refreshState = .startRefresh
        
        isRefreshing = true
        
        var inset = sv.contentInset
        
        inset.top += maxOffSetY
        
        sv.contentInset = inset
        
        
    }

    
    /// 结束刷新
    func endRefreshing() {
        
        guard let sv = scrollView else{
            return
        }
        
        // 正在刷新直接返回
        if refreshView.refreshState != .startRefresh {
            return
        }
        
        // 恢复偏移
        var inset = sv.contentInset
        
        inset.top -= maxOffSetY
        
        sv.contentInset = inset
        
        // 还原状态
        refreshView.refreshState = .normal
        
        isRefreshing = false
        
    }
    
    
    /// 设置UI
    private func setupUI() {
    
        backgroundColor = superview?.backgroundColor
        
        // 超出边界不显示
        //clipsToBounds = true
        
        // 实例化内容（从xib加载，默认是xib中指定的高度）
        addSubview(refreshView)
        
        // 布局refreshView（用纯代码布局，需要指定宽、高）
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: refreshView.bounds.width))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: refreshView.bounds.height))
        
    }
    
}
